#!/bin/bash

# Flowable 非 Docker 安装脚本

set -e

echo "=========================================="
echo "Flowable 非 Docker 安装脚本"
echo "=========================================="
echo ""

# 检查 Java
echo "检查 Java 环境..."
if ! command -v java &> /dev/null; then
    echo "❌ Java 未安装，请先安装 JDK 8+"
    echo "   下载地址: https://www.oracle.com/java/technologies/downloads/"
    exit 1
fi

JAVA_VERSION=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2 | sed '/^1\./s///' | cut -d'.' -f1)
if [ "$JAVA_VERSION" -lt 8 ]; then
    echo "❌ Java 版本过低，需要 JDK 8 或更高版本"
    exit 1
fi

echo "✅ Java 版本: $(java -version 2>&1 | head -n 1)"

# 检查 MySQL
echo ""
echo "检查 MySQL 连接..."
if ! command -v mysql &> /dev/null; then
    echo "⚠️  MySQL 客户端未安装，请确保 MySQL 服务已运行"
else
    echo "✅ MySQL 客户端已安装"
fi

# 创建目录
echo ""
echo "创建必要的目录..."
mkdir -p flowable/downloads
mkdir -p flowable/install
mkdir -p flowable/logs
mkdir -p flowable/config
echo "✅ 目录创建完成"

# 下载 Flowable（如果未下载）
FLOWABLE_VERSION="6.8.0"
FLOWABLE_ZIP="flowable-${FLOWABLE_VERSION}.zip"
FLOWABLE_URL="https://github.com/flowable/flowable-engine/releases/download/flowable-${FLOWABLE_VERSION}/${FLOWABLE_ZIP}"

if [ ! -f "flowable/downloads/${FLOWABLE_ZIP}" ]; then
    echo ""
    echo "下载 Flowable ${FLOWABLE_VERSION}..."
    echo "如果下载失败，请手动下载并解压到 flowable/install 目录"
    echo "下载地址: ${FLOWABLE_URL}"
    
    if command -v wget &> /dev/null; then
        wget -O "flowable/downloads/${FLOWABLE_ZIP}" "${FLOWABLE_URL}" || {
            echo "⚠️  自动下载失败，请手动下载"
            echo "   下载地址: ${FLOWABLE_URL}"
            echo "   保存到: flowable/downloads/${FLOWABLE_ZIP}"
        }
    elif command -v curl &> /dev/null; then
        curl -L -o "flowable/downloads/${FLOWABLE_ZIP}" "${FLOWABLE_URL}" || {
            echo "⚠️  自动下载失败，请手动下载"
            echo "   下载地址: ${FLOWABLE_URL}"
            echo "   保存到: flowable/downloads/${FLOWABLE_ZIP}"
        }
    else
        echo "⚠️  未找到 wget 或 curl，请手动下载"
        echo "   下载地址: ${FLOWABLE_URL}"
        echo "   保存到: flowable/downloads/${FLOWABLE_ZIP}"
    fi
fi

# 解压 Flowable
if [ -f "flowable/downloads/${FLOWABLE_ZIP}" ] && [ ! -d "flowable/install/flowable-${FLOWABLE_VERSION}" ]; then
    echo ""
    echo "解压 Flowable..."
    unzip -q "flowable/downloads/${FLOWABLE_ZIP}" -d flowable/install/
    echo "✅ 解压完成"
fi

# 配置数据库
echo ""
echo "=========================================="
echo "数据库配置"
echo "=========================================="
echo ""
echo "请确保 MySQL 服务已运行，并执行以下 SQL 创建数据库："
echo ""
echo "CREATE DATABASE flowable CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
echo "CREATE USER 'flowable'@'localhost' IDENTIFIED BY 'flowable123';"
echo "GRANT ALL PRIVILEGES ON flowable.* TO 'flowable'@'localhost';"
echo "FLUSH PRIVILEGES;"
echo ""
read -p "数据库已配置完成？(y/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "请先配置数据库，然后重新运行此脚本"
    exit 1
fi

# 创建配置文件
echo ""
echo "创建配置文件..."
cat > flowable/config/application.properties << 'EOF'
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/flowable?characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=flowable
spring.datasource.password=flowable123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Flowable 配置
flowable.database-schema-update=true
flowable.async-executor-activate=true

# 服务器配置
server.port=8080
EOF

echo "✅ 配置文件已创建: flowable/config/application.properties"
echo "   请根据需要修改数据库连接信息"

# 创建启动脚本
echo ""
echo "创建启动脚本..."

cat > flowable/start_standalone.sh << 'EOF'
#!/bin/bash

# Flowable 独立应用启动脚本

FLOWABLE_DIR="flowable/install/flowable-6.8.0"
CONFIG_DIR="flowable/config"

if [ ! -d "$FLOWABLE_DIR" ]; then
    echo "❌ Flowable 未安装，请先运行 install_standalone.sh"
    exit 1
fi

echo "启动 Flowable UI..."
cd "$FLOWABLE_DIR/wars/flowable-ui"
java -Xms512m -Xmx1024m \
     -Dspring.config.location=../../../../config/application.properties \
     -jar flowable-ui.war > ../../../../logs/flowable-ui.log 2>&1 &

echo "Flowable UI 已启动，PID: $!"
echo "日志文件: flowable/logs/flowable-ui.log"
echo "访问地址: http://localhost:8080/flowable-ui"
echo ""
echo "启动 Flowable REST API..."
cd "$FLOWABLE_DIR/wars/flowable-rest"
java -Xms512m -Xmx1024m \
     -Dspring.config.location=../../../../config/application.properties \
     -Dserver.port=8081 \
     -jar flowable-rest.war > ../../../../logs/flowable-rest.log 2>&1 &

echo "Flowable REST API 已启动，PID: $!"
echo "日志文件: flowable/logs/flowable-rest.log"
echo "访问地址: http://localhost:8081/flowable-rest"
echo ""
echo "等待服务启动（约 30 秒）..."
sleep 30

echo ""
echo "=========================================="
echo "服务启动完成"
echo "=========================================="
echo "Flowable UI: http://localhost:8080/flowable-ui"
echo "默认账号: admin / test"
echo ""
echo "Flowable REST API: http://localhost:8081/flowable-rest"
echo ""
echo "查看日志: tail -f flowable/logs/flowable-ui.log"
echo "停止服务: pkill -f flowable-ui.war && pkill -f flowable-rest.war"
EOF

chmod +x flowable/start_standalone.sh
echo "✅ 启动脚本已创建: flowable/start_standalone.sh"

echo ""
echo "=========================================="
echo "安装完成"
echo "=========================================="
echo ""
echo "下一步："
echo "1. 检查并修改 flowable/config/application.properties 中的数据库配置"
echo "2. 运行启动脚本: ./flowable/start_standalone.sh"
echo "3. 部署流程文件: cd flowable && python deploy_all.py"
echo ""

